package top.likeqc.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import top.likeqc.common.lang.Result;
import top.likeqc.entity.Target;
import top.likeqc.entity.TargetPoint;
import top.likeqc.service.ICourseService;
import top.likeqc.service.IPointService;
import top.likeqc.service.ITargetPointService;
import top.likeqc.service.ITargetService;

import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 目标支撑(目标-课程指标点) 前端控制器
 * </p>
 *
 * @author likeqc
 * @since 2022-04-14
 */
@RestController
@RequestMapping("/targetPoint")
public class TargetPointController extends BaseController {

    @Autowired
    ITargetPointService targetPointService;

    @Autowired
    ITargetService targetService;

    @Autowired
    ICourseService courseService;

    @Autowired
    IPointService pointService;

    @GetMapping()
    public Result list(@RequestParam("courseId") String key) {

        List<Target> targetList = targetService.list(new QueryWrapper<Target>().eq("course_id", key));

        Set<Long> targetIds = targetList.stream().map(target -> target.getId()).collect(Collectors.toSet());

        // 防止 targetIds 为空
        targetIds.add(-1L);

        Page<TargetPoint> page = targetPointService.page(getPage(),
            new QueryWrapper<TargetPoint>().in("target_id", targetIds));
        // 获取指标点的信息

        if (!page.getRecords().isEmpty()) {
            page.getRecords().forEach(targetPoint -> {
                targetPoint.setPoint(pointService.getById(targetPoint.getPointId()));
                targetPoint.setTarget(targetService.getById(targetPoint.getTargetId()));
            });
        }
        return Result.success(page);
    }

    @PostMapping()
    public Result edit(@RequestBody TargetPoint target) {
        boolean save = targetPointService.saveOrUpdate(target);
        if (save) {
            return Result.success();
        } else {
            return Result.fail("新增、修改课程目标，操作失败");
        }
    }

    @DeleteMapping()
    public Result delete(@RequestBody List<Integer> ids) {
        boolean b = targetPointService.removeByIds(ids);
        if (b) {
            return Result.success();
        } else {
            return Result.fail("删除目标支撑，操作失败");
        }
    }


}
